package cn.com.ytst.data.integration.controller;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.datax.common.util.Configuration;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.ytst.framework.common.StringTools;

import cn.com.ytst.data.integration.CommonKey;
import cn.com.ytst.data.integration.manager.job.QuartzManager;
import cn.com.ytst.data.integration.util.PageUtil;
import cn.com.ytst.data.integration.util.filter.FileFilter;
import cn.com.ytst.data.integration.vo.AjaxResult;
import cn.com.ytst.data.integration.vo.DataTable;




/**
 * @ClassName FileController
 * @Descrption TODO
 * @Version 1.0
 * @Author 123774135@qq.com
 * @date 2020/7/2 12:12
 */
@Controller
@RequestMapping
public class FileController {

    private Logger logger = LoggerFactory.getLogger(FileController.class);

    @Value("${filepath}")
    private String filepath ;


    private static final String LINE_TAG = "/";

    private static final String POINT_TAG = ".";
    
//    @Autowired
//    private Hander fileReaderHander;

    @Autowired
    private QuartzManager quartzManager;

    @RequestMapping(value = "/file/grid", method = RequestMethod.POST)
    @ResponseBody
    public DataTable<JSONObject> grid(HttpServletRequest request) throws IOException {
        String pageNumber = StringTools.isBlank(request.getParameter("pageNum"))?"1":request.getParameter("pageNum");
        String pageSize =  StringTools.isBlank(request.getParameter("pageSize")) ? "10":request.getParameter("pageSize");
        List<File> list = FileFilter.fiterFile(filepath+File.separator+"file", "file");
        JSONObject value = new JSONObject();


        List<JSONObject> list_json = Lists.newArrayList();
        if (!list.isEmpty()) {
            for (File f : list) {
                JSONObject jsonObject = new JSONObject();
                Configuration configuration = Configuration.from(FileUtils.readFileToString(f, "utf-8"));
                String jobname = configuration.getString(CommonKey.FILE_READER_JOBNAME_TAG);
                String className = configuration.getString(CommonKey.FILE_READER_CLASS_NAME_TAG);
                String pluginjar = configuration.getString(CommonKey.FILE_READER_PLUGINJAR_TAG);
                String cronexpress = configuration.getString(CommonKey.FILE_READER_CRONEXPRESS_TAG);
                String path = configuration.getString(CommonKey.FILE_READER_FILEPATH_TAG);
                jsonObject.put("jobname", jobname);
                jsonObject.put("pluginjar", pluginjar);
                jsonObject.put("className", className);
                jsonObject.put("filepath", path);
                jsonObject.put("id", f.getName());
                jsonObject.put("cronexpress", cronexpress);
                //String status = "";
                //String previousFireTime = "";
                //String nextFireTime = "";
//					TriggerState triggerState =	quartzManager.triggerState(name, TaskManager.GROUP_NAME);
//					if(null == triggerState) {
//						status = "不存在";
//					}else {
//						String state = triggerState.name();
//						switch (state) {
//						case "NONE":
//							status = "不存在";
//							break;
//						case "NORMAL":
//							status = "正常";
//							break;
//						case "PAUSED":
//						status = "停止";
//						break;
//						case "COMPLETE":
//							status = "完成";
//							break;
//						case "ERROR":
//							status = "错误";
//							break;
//						case "BLOCKED":
//							status = "阻塞中";
//							break;
//						default:
//							break;
//						}
//						Trigger trigger = 	quartzManager.getTrigger(name);
//						if(null == trigger) {
//
//						}else {
//							nextFireTime = DateUtil.formatDate(trigger.getNextFireTime(),DateUtil.format1);//下次触发时间
//							previousFireTime = null == trigger.getPreviousFireTime() ? "" : DateUtil.formatDate(trigger.getPreviousFireTime(), DateUtil.format1)	;//上一次触发时间
//						}
                //}
//					jsonObject.put("status", status);
//					jsonObject.put("nextFireTime", nextFireTime);
//					jsonObject.put("previousFireTime", previousFireTime);
                list_json.add(jsonObject);
            }
        }

        DataTable<JSONObject> dataTable = new DataTable<>();
        dataTable.setRows(PageUtil.startPage(list_json,Integer.parseInt(pageNumber),Integer.parseInt(pageSize)));
        dataTable.setTotal(list_json.size());
        dataTable.setCode(0);
        dataTable.setMsg("");
        return dataTable;

    }


    @RequestMapping(value = "/file/add", method = RequestMethod.GET)
    public ModelAndView add() {
        return new ModelAndView("/page/component/file/file-add");
    }



    @RequestMapping(value="/file/save",method= RequestMethod.POST)
    @ResponseBody
    public AjaxResult save(HttpServletRequest request) {
        String path = request.getParameter("filepath");
        String name = request.getParameter("name");
        String jobname = request.getParameter("jobname");
        String pluginjar = request.getParameter("pluginjar");
        String corn = request.getParameter("corn");
        String split = request.getParameter("split");
        String className = request.getParameter("className");
        String scanpackage = request.getParameter("scanpackage");
        File file = new File(filepath + File.separator + "file" + "/file_" + jobname.toLowerCase() + ".json");

        try {
            String str = FileUtils.readFileToString(new File(filepath + "/temp/file_temp.json"), "utf-8");
            FileUtils.write(file, str, "utf-8");//先预先创建一个文件

            Configuration configuration = Configuration.from(file);
            configuration.set(CommonKey.FILE_READER_JOBNAME_TAG,jobname);
            configuration.set(CommonKey.FILE_READER_SCANPACKAGE_TAG, scanpackage);
            configuration.set(CommonKey.FILE_READER_PLUGINJAR_TAG,pluginjar);
            configuration.set(CommonKey.FILE_READER_CLASS_NAME_TAG,className);
            configuration.set(CommonKey.FILE_READER_NAME_TAG,name);
            configuration.set(CommonKey.HTTP_CORN_TAG,corn);
            configuration.set(CommonKey.FILE_READER_FILEPATH_TAG,path);
            configuration.set(CommonKey.FILE_READER_DATASPLIT_TAG,split);

            configuration.set(CommonKey.FILE_READER_DATAENCODE_TAG,"utf-8");

            String json = configuration.beautify();
            FileUtils.write(file, json, "utf-8");//先预先创建一个文件
            return AjaxResult.success(jobname + "添加成功!");
        } catch (IOException e) {
            logger.error("", e);
        }
        return AjaxResult.error(jobname + "添加失败!");

    }

    @RequestMapping(value = "/file/edit/{id}", method = RequestMethod.GET)
    public ModelAndView edit(@PathVariable(value = "id") String id) {
        Configuration configuration = Configuration.from(new File(filepath+File.separator+"file"+LINE_TAG+id));
        Set<String> set = configuration.getKeys();
        Map<String,Object> map = Maps.newHashMap();
        for(String key : set) {
            int last_index = key.lastIndexOf(POINT_TAG);
            String end_key = key.substring(last_index+1);
            map.put(end_key, configuration.get(key));
        }

        map.put("id", id);
        return  new ModelAndView("/page/component/file/file-edit",map);

    }


    @RequestMapping(value="/file/update",method= RequestMethod.POST)
    @ResponseBody
    public AjaxResult update(HttpServletRequest request) {
        String path = request.getParameter("filepath");
        String name = request.getParameter("name");
        String jobname = request.getParameter("jobname");
        String pluginjar = request.getParameter("pluginjar");
        String corn = request.getParameter("corn");
        String split = request.getParameter("split");
        String id =  request.getParameter("id");
        String className = request.getParameter("className");
        String scanpackage = request.getParameter("scanpackage");
        File file = new File(filepath+File.separator+"file"+File.separator+id);
        try {
            Configuration configuration = Configuration.from(file);
            configuration.set(CommonKey.FILE_READER_JOBNAME_TAG,jobname);
            configuration.set(CommonKey.FILE_READER_PLUGINJAR_TAG,pluginjar);
            configuration.set(CommonKey.FILE_READER_CLASS_NAME_TAG,className);
            configuration.set(CommonKey.FILE_READER_NAME_TAG,name);
            configuration.set(CommonKey.HTTP_CORN_TAG,corn);
            configuration.set(CommonKey.FILE_READER_FILEPATH_TAG,path);
            configuration.set(CommonKey.FILE_READER_DATASPLIT_TAG,split);
            configuration.set(CommonKey.FILE_READER_SCANPACKAGE_TAG, scanpackage);
            configuration.set(CommonKey.FILE_READER_DATAENCODE_TAG,"utf-8");
            String json = configuration.beautify();
            FileUtils.write(file, json, "utf-8");//先预先创建一个文件
            return AjaxResult.success(file+"编辑成功!");
        } catch (IOException e) {
            logger.error("", e);
        }
        return AjaxResult.error(file+"编辑失败!");

    }

    @RequestMapping(value="/file/remove",method= RequestMethod.POST)
    @ResponseBody
    public AjaxResult stop(String ids) {
        try {
            File f = new File(filepath+LINE_TAG+"file"+LINE_TAG+ids);

            FileUtils.forceDelete(f);
            return AjaxResult.success(ids+"删除成功!");
        } catch (Exception e) {
            logger.error("", e);
        }
        return AjaxResult.error(ids+"删除失败!");

    }
    
	//hander
//	@RequestMapping(value="/file/hander",method= RequestMethod.POST)
//    @ResponseBody
//    public AjaxResult hander(String id) {
//    	try {
//    		new DefaultEngine(fileReaderHander).start(new File(filepath+LINE_TAG+"file"+LINE_TAG+id));
//			return AjaxResult.success(id+"作业操作成功!");
//		} catch (Exception e) {
//			logger.error("", e);
//		}
//    	 return AjaxResult.error(id+"作业操作失败!");
//
//    }
//    
//    public static void main(String[] args) {
//		new DefaultEngine(new FileReaderHander()).start(new File("D:\\job\\file\\file_event_process.json"));;
//	}
}
